var recordID;
var maxrows = 25;
var myLocation;
var watchId;
var trackOn = false;
var geoCount = 0;
var myLat = 41.99;
var myLon = -72.88;
var zoom = 6;
var autoSearch = true;
var firstTime = true;	

var latlng, center, geocoder;
var myLocations = [];
var map, map2;
var points;
var point;
var markerArray = [];
var markerArray2 = [];
var marker;
var html;
var currentMarkerIndex = -1;
var centerMarker;
	var icons = [
		'http://maps.google.com/mapfiles/ms/micons/blue.png',
		'http://maps.google.com/mapfiles/ms/micons/red.png',
		'http://maps.google.com/mapfiles/ms/micons/yellow.png'
	];
var llb; //latlngbounds

var searchControl;
google.load('search', '1.0');
google.setOnLoadCallback(searchLoad, true);


$(document).ready(function() {
	initialize();
});

function initialize(){
	debugMessage('<h3>debug messages</h3>');
	debugMessage('initialize()');
	recordID = window.location.hash;
//	if($.cookie('myLat')!==null) {myLat = $.cookie('myLat');}
//	if($.cookie('myLon')!==null) {myLon = $.cookie('myLon');}
//	if($.cookie('zoom')!==null) {zoom = 1 * $.cookie('zoom');}
	setupMap();
	setupMap2();

	$("#locateButton").click(function () {
		searchMap();
	});
//	setupHelp();
//	$('#left').draggable();
//	$('#left').resizable();
//	$('#middleright').draggable();
//	$('#middleright').resizable();

}

function searchMap(){
	debugMessage('searchMap()');
	var location =  $('#locateText').attr('value');
	if(location!=='') {
		geocoder.geocode(
			{
				'address' : location
			},
			function(results,status){
				if(status==google.maps.GeocoderStatus.OK) {
					ll = results[0].geometry.location;
					map.setCenter(ll);
					myLat = ll.lat();
					myLon = ll.lng();
					getPlaces();
				}
				else {
//					alert('issue with geocoder, status='+status);
				}
			}
		);	
	}
} //searchMap()



function getPlace(id){
	debugMessage('getPlace('+id+')');
	$.ajax({
		url: 'getplace.php',
		data: {
			table:'boats',
			recordID: id
			},
	  	success: function(data) {
			debugMessage('getPlace - success');
			var points = eval(data);
			var tp = points.results[0];
			myLat = tp.lat;
			myLon = tp.lon;	
			name = tp.name;
			latlng = new google.maps.LatLng(myLat, myLon);
			map.setCenter(latlng);
			window.location.hash = id;
			getPlaces();
		}
	});
}  //getPlace()

function getPlaces(){
	debugMessage('getPlaces()');
//	llb = new google.maps.LatLngBounds(map.getCenter());
//	$('#tabs').tabs('select',0);
	bounds = map.getBounds();
//	center = map.getCenter();
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();
	$.ajax({
		url: 'getplaces.php',
		data: {
			table:'boats',
//			ctrlat: center.lat(),
//			ctrlon: center.lng(),
			ctrlat: myLat,
			ctrlon: myLon,
			swlat: sw.lat(),
			swlon: sw.lng(),
			nelat: ne.lat(),
			nelon: ne.lng(),
			count: maxrows,
			type:'%' //wildcard
			},
	  	success: function(data) {
	  		debugMessage('getPlaces - success');
			var points = eval(data);
			var dataHtml = '';
			if(points.total>0){
			clearMarkers(markerArray);
			currentMarkerIndex = -1;
			for(i=0;i<points.total;i++){
				var tp = points.results[i];
//				var js = '<a  id="markers'+markerArray.length+'" href="#">'+tp.name+'</a>';
				var js = '<a class="displayPoint" id="markers'+markerArray.length+'" href="#">'+tp.name+'</a><br>';
//				js += '('+tp.type+')<br>';
				dataHtml += js;
				var marker = createMarker(map, tp.name, tp.lat, tp.lon, 0, markerArray.length, true, tp);
				if(i==0){
					displayPoint(0);
				}
//				llb.extend(new google.maps.LatLng(tp.lat,tp.lon));			
			}
			
//			map.fitBounds(llb);
//			map.setCenter(llb.getCenter());
//			myLat = map.getCenter().lat();
//			myLon = map.getCenter().lng();
			
			
			$('#data').html(dataHtml);
//			$('#message').html('click on marker for detail');
			$(".displayPoint").click(function(event){
				var ev = event.currentTarget;
				var id = ev.id.substring(7,99);
				var marker = markerArray[id];
				google.maps.event.trigger(marker,'click');
//				marker.setIcon(icons[1]);
//				displayPoint(id);
//				$('#tabs').tabs('select',1);			
			});			
			}
		}
	});
} // getPlaces()

function displayPoint(markerIndex){
	var city, county, state_abbr = '';
	debugMessage('displayPoint()');
	$('#place').html('');
	$('#weather').html('');
	html = '';
	var m = markerArray[markerIndex];
	var pt = m.getPosition();
	var lat = pt.lat();
	var lon = pt.lng();
	var latlon = lat + ', ' + lon;
	var ll = 'lat='+lat+'&lng='+lon;
	var latlng = new google.maps.LatLng(lat, lon);
	var id = m.details.id;
	recordID = m.details.id;
	var name = m.title;
	var url = m.details.url;
//	var town = m.details.town;
	var state = m.details.state;
	var distance = m.details.distance;
	var source = m.details.source;
	var type = m.details.type;
	var description = m.details.description;
	$('#placename').html('<h3>'+name+'</h3>');

	var droidDirections 	= "geo:"+latlon+"?q="+latlon; 
	var geoNamesWiki 	= 'http://ws.geonames.org/findNearbyWikipediaJSON?maxRows=5&'+ll;
	var NOAAQuickForecast   = 'http://forecast.weather.gov/afm/PointClick.php?lat='+lat+'&lon='+lon;
	var NOAAWeather 	= 'http://forecast.weather.gov/MapClick.php?textField1='+lat+'&textField2='+lon;
	var NOAAWeatherText 	= 'http://forecast.weather.gov/MapClick.php?textField1='+lat+'&textField2='+lon+'&TextType=1';
	var googleSearch 	= 'http://google.com/search?q=%27'+name+'%27%20'+state+'%20paddling';

	var zipcode = null;
	
	$.ajax({
		url: 'getweather.php',
		data: {
			lat: lat,
			lon: lon
			},
	  	success: function(data) {
  			$('#weather').html('<a href="'+NOAAWeather+'" target="_blank">Detail</a><br>'+data+'<br>');
		}
	});

	html = '<table>';
	linkAdd('Source',url, source);
	tablePair('id',recordID);
	tablePair('type',type);
	tablePair('distance',distance+' miles');
	tablePair('lat, lon',latlon);
	tablePair('description',description);		
//	linkAdd('Search',googleSearch, 'Google search');
//	linkAdd('Weather',NOAAWeather, 'NOAA Weather');
//	linkAdd('Weather',NOAAWeatherText, 'NOAA Weather text');
//	linkAdd('Names',geoNamesWiki, 'GeoNames Wiki');
	
	marker2 = createMarker(map2, name, lat, lon, 1, 1, false, 'asdf');
	if(currentMarkerIndex>-1){
		markerArray[currentMarkerIndex].setIcon(icons[0]);
		markerArray[currentMarkerIndex].setAnimation(null);
	}
	currentMarkerIndex = markerIndex;
	markerArray[markerIndex].setIcon(icons[1]);
	markerArray[markerIndex].setAnimation(google.maps.Animation.BOUNCE);
	markerArray[markerIndex].setZIndex(9999);
	marker2.setMap(map2);
	if($('#map2').css('visibility')=='hidden'){
		$('#map2').css('visibility','visible');
//		$('#place').css('visibility','visible');
	}
	ctr = new google.maps.LatLng(lat,lon);
	map.panTo(ctr);
	map2.panTo(ctr); 

//	html += '<table>';
//  	$('#place').html(html);
  	window.location.hash = recordID;
	geocoder.geocode(
		{
		'location' : latlng
		},
		function(results,status){
			if(status==google.maps.GeocoderStatus.OK) {
				for (i in results[0].address_components) {
					var t = results[0].address_components[i];					
					for (x in t.types){
						if(t.types[x]=='administrative_area_level_1'){
							state = t.long_name;
							state_abbr = t.short_name;
						}
						if(t.types[x]=='administrative_area_level_2'){
							county = t.long_name;
						}
						if(t.types[x]=='locality'){
							city = t.long_name;
						}
					}
				}
				tablePair('city',city);
				tablePair('county',county);
				tablePair('state',state); // overrides database
				linkAdd('google map','http://google.com/maps?q='+latlng,name);
//				linkAdd('wiki','http://www.jimdevoe.com/mediawiki-1.15.1/index.php5?title='+state_abbr,'page='+state_abbr);
				html += '<table>';
				$('#place').html(html);
				searchControl.execute(name+' '+city+' '+state+' "paddling OR paddle"');
			}
			else {
				html += '<table>';
				$('#place').html(html);
				searchControl.execute(name+' '+state+' "paddling OR paddle"');
			}
		}
	);	
	/*
	$.ajax({
		url: 'http://ws.geonames.org/findNearbyWikipediaJSON',
		data: {
			lat: lat,
			lng: lon,
			maxRows: 4
			},
	  	success: function(data) {
	  		html ='<h3>Wikipedia</h3>';
			for (i=0;i<data.geonames.length;i++) {
				buttonAdd(data.geonames[i].title, 'http://'+data.geonames[i].wikipediaUrl);
				html += '<p>' + data.geonames[i].summary + '</p>';
			}
			$('#place').append(html);
		}
	});
	*/
}


function createMarker(map, name, lat, lon, iconIndex, arrayIndex, saveMarker, pointDetails){
//	debugMessage('createMarker()');
	var point = new google.maps.LatLng(lat, lon);
	var marker = new google.maps.Marker({
		position: 	point,
		map: 		map,
		icon: 		icons[iconIndex],
		title: 		name,
		details:	pointDetails
	});	
	marker.setMap(map);
	if(saveMarker) {
		markerArray.push(marker);
		google.maps.event.addListener(marker, 'click', function() {
//			debugMessage('marker listener: click');
			displayPoint(arrayIndex);
			if(marker.getAnimation(google.maps.Animation.BOUNCE)){} 
			else {marker.setAnimation(google.maps.Animation.BOUNCE);};
		});
	};
	return marker;
} // displayPoint()

function clearMarkers(markers) {
	debugMessage('clearMarkers()');
	if (markers) {
		for (i in markers) {
			markers[i].setMap(null);
		}
	markers.length = 0;
	}
}

function tablePair(label, value){
//	debugMessage('tablePair()');
	if(value) {
		html += '<tr><td><b>'+label+':</b></td><td>'+value+'</td></tr>';
	} 
}

function buttonAdd(label, href){
//	debugMessage('buttonAdd()');
	if(href){
		html +=  '<button type="button" onclick="window.open('+"'"+href+"'"+')">'+label+'</button>';
	}
}

function linkAdd(tableLabel,href, linkLabel){
//	debugMessage('linkAdd()');
	if(href){
		html += '<tr><td><b>'+tableLabel+':</b></td><td><a href="'+href+'" target="_blank">'+linkLabel+'</a></td></tr>';
	}
}

function getCookies(){
	debugMessage('getCookies');
	if($.cookie('myLat')!==null) {myLat = $.cookie('myLat');}
	if($.cookie('myLon')!==null) {myLon = $.cookie('myLon');}
	if($.cookie('zoom')!==null) {zoom = 1 * $.cookie('zoom');}
}


function saveCookies(){
	debugMessage('saveCookies');
	$.cookie('myLat',map.getCenter().lat(),{expires:7});
	$.cookie('myLon',map.getCenter().lng(),{expires:7});
	$.cookie('zoom',map.getZoom(),{expires:7});
}

function searchLoad(){
		searchControl = new google.search.SearchControl();
		var options = new google.search.SearcherOptions();
		options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
		searchControl.addSearcher(new google.search.WebSearch(), options);
//		searchControl.addSearcher(new google.search.LocalSearch(), options);
		searchControl.draw(document.getElementById("searchcontrol"));
} // searchLoad()

function setupHelp(){
	helpOptions = {
		position: 'center',
		width: '400px'
	};
	$('.helpText').hide();
	$('#searchTitle').hover(
		function(){
			html = '';
			html += '<p><b>center</b> map using mouse - when you see the little hand with all fingers spread, hold down the left button and drag map around.</p>';
			html += '<p><i>if the hand is pointing with a <b>finger</b>, then you are on a <b>hot spot</b> - either a map control, or a marker, or some other doodad that will behave differently.  Watch out for the pointing figer, the map will not move around if the finger is up.</i></p>';
			html += '<p>when done dragging, a <b>single left click</b> anywhere on the map itself (other than hot-spots - see above) to update display with nearest boat launches.</p>';
			html += '<p>you can also <b>type in an address</b> and press <b>"locate"</b>, the map will re-center and re-load nearest boat launches.</p>';
			html += '<p>a <b>red marker</b> indicates the currently highlighted launch - with details on the right part of the screen.</p>'; 
			html += '<p>click on any <b>blue marker</b> - and in this case, the pointy finger is a good thing, indicating that you are hovering over a hot spot - to highlight that location. or, click on one of the <b>names</b> below.</p>';
			html += '<p>if you have trouble, try zooming out a bit and re-click on map.  Also, data is not available in all regions, try east coast for now ;) </p>';
			html += '<p>if you have a mouse with a wheel in the middle, try rolling it - the map should zoom in and out as you roll the wheel.  If you do not have a wheel, use the + and - symbols on the map to zoom in and out.</p>';
			$('#helpMapText').html(html);
//			$('#helpMapText').toggle('slow');
			$('#helpMapText').dialog(helpOptions);
		},
		function(){
			$('#helpMapText').dialog('close');
		}
	);
	
	$('#localMapTitle').hover(
		function(){
			html = '';
			html += '<p>you should have a <b>satellite view</b> of the boat launch and local <b>weather report</b> below the map.</p>';
			html += '<p>the map can be changed through a number of <b>controls</b> (little boxes, +/- sign, human figure, etc), click on some and see what happens.</p>';
			html += '<p>if you <b>get lost</b>, go back to the search map (on left) and re-click on the red marker, it will reset your center map.</p>';
			html += '<p>the <b>detail</b> link will take you to the NOAA site for more detailed weather.</p>';
			$('#helpMap2Text').html(html);
			$('#helpMap2Text').dialog(helpOptions);
		},
		function(){
			$('#helpMap2Text').dialog('close');
		}
	);

	$('#googleSearchTitle').hover(
		function(){
//			$('#helpMapText').toggle('slow');
	html = '';
	html += '<p>below are <b>google search</b> results based on this location plus the keywords <b>"paddle OR paddling"</b></p>';
	html += '<p>these should be the exact same results you would get if you typed in the name of this boat launch plus the state abbreviation plus the "paddle OR paddling" keyword phrase into a google search window.</p>';
	$('#helpGoogleSearchText').html(html);
			$('#helpGoogleSearchText').dialog(helpOptions);

		},
		function(){
			$('#helpGoogleSearchText').dialog('close');
		}
	);
}

function debugMessage(msg) {
	if(false){
		$('#debugMessage').append(msg+'<br>');
	}
}	
	function setupMap(){
	debugMessage('setupMap()');
	latlng = new google.maps.LatLng(myLat, myLon);
	center = latlng;
	geocoder = new google.maps.Geocoder();

	var myOptions = {
		zoom: zoom,
		center: center,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: true,
		streetViewControl: false,
		mapTypeControl: false,
		navigationControlOptions: {
			position: google.maps.ControlPosition.TOP_LEFT
		}
	};
 
	map = new google.maps.Map(document.getElementById("map"), myOptions);

	google.maps.event.addListener(map, 'click', function(a){
		debugMessage('map listener - click');
		myLat = a.latLng.lat();
		myLon = a.latLng.lng();
		getPlaces();
	});
	google.maps.event.addListener(map, 'idle', function(){
		debugMessage('map listener - idle');
		if(autoSearch){
			debugMessage('map listener - idle - autoSearch');
			autoSearch = false;
//			getPlaces();		
		};
		saveCookies();
	});
	google.maps.event.addListener(map, 'tilesloaded', function(){
		debugMessage('map: tiles loaded');
		if(firstTime){
			debugMessage('map: tiles loaded - first time');
			firstTime = false;
			if(recordID) {
				debugMessage('recordID '+ recordID + ' detected');
				recordID = recordID.substr(1)*1;
				getPlace(recordID);
			} else {
				getPlaces();
			}
		};
	});
	}		// setupMap()

	function setupMap2() {
		debugMessage('setupMap2()');
		var myOptions2 = {
			zoom: 17,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.SATELLITE,
			navigationControl: true,
			navigationControlOptions: {
				position: google.maps.ControlPosition.TOP_LEFT
			},
			scaleControl: false,
			scaleControlOptions: {
				position: google.maps.ControlPosition.LEFT
			},
			streetViewControl: false
		};
		map2 = new google.maps.Map(document.getElementById("map2"), myOptions2);
	}

